package com.changyinBus.web.controller.web;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.changyinBus.common.core.controller.BaseController;
import com.changyinBus.common.core.domain.AjaxResult;
import com.changyinBus.common.core.domain.entity.SysArticle;
import com.changyinBus.common.core.domain.entity.SysLotteryRecords;
import com.changyinBus.common.core.domain.entity.SysTransfer;
import com.changyinBus.common.core.domain.entity.SysWxInfo;
import com.changyinBus.common.core.redis.RedisCache;
import com.changyinBus.common.utils.IDGenerator;
import com.changyinBus.common.utils.WebUtils;
import com.changyinBus.system.service.*;
import com.changyinBus.web.controller.bean.WeChatUserInfo;
import com.changyinBus.web.controller.service.CsrcBankService;
import com.changyinBus.web.controller.service.WeChatJsApiService;
import com.changyinBus.web.controller.service.WeChatTransferService;
import com.changyinBus.web.controller.service.WeChatWebLoginService;
import com.changyinBus.web.controller.weChartPay.bean.WeChatPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RestController
public class IndexController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private IRaffleService raffleService;
    @Resource
    private CsrcBankService bankService;
    @Resource
    private WeChatWebLoginService weChatWebLoginService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private WeChatTransferService transferService;
    @Resource
    private ISysWxInfoService sysWxInfoService;
    @Resource
    private ISysLotteryRecordsService sysLotteryRecordsService;
    @Resource
    private WeChatPayConfig config;
    @Resource
    private WeChatJsApiService weChatJsApiService;
    @Resource
    private ISysTransferService sysTransferService;
    @Resource
    private ISysArticleService articleService;

    /**
     * 首页
     * @return
     */
    @GetMapping("/web/index/{openid}")
    public ModelAndView zindex(@PathVariable String openid, @RequestParam(required = false,defaultValue = "") String token) {
        if(openid==null){
            return new ModelAndView("error");
        }
        //openid提交银行校验
        //boolean flag = bankService.verifyUser(openid);
        boolean flag = true;        //测试继续
        int num = 0;
        //前端步骤
        int step = 0;
        SysLotteryRecords sysLotteryRecords = null;
        //校验成功 openid为常银真实用户 才能进入抽奖
        if(flag){
            if("".equals(token)){
                //无token回调，第一次访问 点击需要微信授权
                step = 1;
            }else{
                //有token回调 去抽奖
                step = 2;
                //根据微信授权回调token获取redis的当前openid
                String user_openid = redisCache.getCacheObject(token);
                if(user_openid != null && !"".equals(user_openid)){
                    //根据open获取用户信息
                    SysWxInfo sysWxInfo = sysWxInfoService.selectByOpenid(user_openid);
                    if(sysWxInfo != null){
                        num = sysWxInfo.getNum();
                        if(num > 0){
                            sysLotteryRecords = sysLotteryRecordsService.selectByOpenid(user_openid);
                        }
                    }
                }else{
                    return new ModelAndView("error");
                }
            }
            return new ModelAndView("index")
                    .addObject("token",token)//uuid
                    .addObject("num",num)
                    .addObject("sysLotteryRecords",sysLotteryRecords)
                    .addObject("step",step)
                    .addObject("openid",openid);
        }else{
            return new ModelAndView("error");
        }
    }

    /**
     * 获取微信登录URL，前端引导用户跳转至此URL
     */
    @GetMapping("/web/auth-url")
    public void getWeChatAuthUrl(String state, HttpServletResponse response) throws Exception{
        response.sendRedirect(weChatWebLoginService.generateAuthUrl(state));;
    }

    /**
     * 微信回调接口 - 处理授权码
     */
    @GetMapping("/web/wechat/callback")
    public void callback(@RequestParam String code,
                           @RequestParam String state,
                           HttpServletResponse response) {
        try {
            // 获取用户信息
            WeChatUserInfo userInfo = weChatWebLoginService.handleCallback(code, state);
            // 存储用户信息
            SysWxInfo info = new SysWxInfo();
            String openid = userInfo.getOpenid();
            if(sysWxInfoService.selectByOpenid(openid) == null){
                info.setOpenid(openid);
                info.setNickname(userInfo.getNickname());
                info.setSex(userInfo.getSex());
                info.setHeadImgUrl(userInfo.getHeadimgurl());
                info.setState(state);
                info.setNum(0);
                sysWxInfoService.insert(info);
            }
            String uuid = weChatWebLoginService.generateState();
            //生成用户令牌存储redis 然后跳转首页 state为常银传的openid
            redisCache.setCacheObject(uuid,openid);
            String redirectUrl = "https://jsck.sy-my.net/web/index/"+state+"?token="+uuid;
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            log.error("微信登录回调处理失败", e);
            //return "redirect:https://your-frontend.com/login-error?msg=" + e.getMessage();
        }
    }

    @GetMapping("/web/lottery")
    public AjaxResult lottery(@RequestParam String uuid,HttpServletRequest request) throws Exception{
        JSONObject result = new JSONObject();
        //再次校验银行openid
//        if(!bankService.verifyUser(sysWxInfo.getState())){
//            return error("用户身份效验失败！");
//        }

        String openId = redisCache.getCacheObject(uuid);
        SysWxInfo info = sysWxInfoService.selectByOpenid(openId);
        if(info == null){
            return error("您当前没有抽奖资格！");
        }
        if(info.getNum() > 0){
            return error("抽奖次数已用完！");
        }

        //拿到常银openid以及当前用户信息 校验无误以后进行抽奖
        SysArticle article = articleService.selectArticleById(202509270925442687L);
        if(sysLotteryRecordsService.getCount(new SysLotteryRecords()) >= Integer.parseInt(article.getHeadTitle())){
            return error("对不起，您来晚了，活动已结束！");
        }
        double lottery = raffleService.lottery(article);
        //存储抽奖信息
        SysLotteryRecords sysLotteryRecords = new SysLotteryRecords();
        sysLotteryRecords.setId(IDGenerator.getID());
        sysLotteryRecords.setMoney(lottery);
        sysLotteryRecords.setOpenid(info.getOpenid());
        sysLotteryRecords.setNickname(info.getNickname());
        sysLotteryRecords.setSex(info.getSex());
        sysLotteryRecords.setHeadImgUrl(info.getHeadImgUrl());
        if(lottery == 0){
            //前台显示未中奖
            sysLotteryRecords.setStatus("N");
        }else{
            //前台显示中奖
            sysLotteryRecords.setStatus("Y");
            //转账开始
            int amount = (int)(lottery*100);
            SysTransfer transfer = new SysTransfer(info,String.valueOf(amount));
            sysTransferService.insertTransfer(transfer);
            //调用微信转账
            JSONObject packageInfo = transferService.transfer(transfer.getOpenId(),Integer.parseInt(transfer.getAmount()), String.valueOf(transfer.getId()),"功能测试");
            String packageStr = packageInfo.getStr("package_info");
            //更新回调第三方流水号
            transfer.setTransferBillNo(packageInfo.getStr("transfer_bill_no"));
            sysTransferService.updateTransfer(transfer);

            JSONObject trans = new JSONObject();
            trans.put("packageInfo",packageStr);
            trans.put("mchId",config.getMchId());
            trans.put("appId",config.getAppId());

            //获取域名
            String currentUrl = WebUtils.getFullDomain(request);
            Map<String, String> wxConfig = weChatJsApiService.getJsApiConfig(currentUrl);
            trans.put("signature", wxConfig.get("signature"));
            trans.put("jsAppId", wxConfig.get("appId"));
            trans.put("nonceStr", wxConfig.get("nonceStr"));
            trans.put("timestamp", wxConfig.get("timestamp"));

            /*trans.put("signature", "b7156f8db59db9eceee2c1c495f5c16ed50ee6f9");
            trans.put("jsAppId", "wxe49005b4e14d4794");
            trans.put("nonceStr", "019bb7f1adfa46df");
            trans.put("timestamp", "1759247296");*/
            System.out.println(trans);
            result.put("trans",trans);
        }
        sysLotteryRecordsService.insert(sysLotteryRecords);
        //更新用户抽奖次数
        sysWxInfoService.incrementNum(info.getOpenid());

        JSONObject lotteryInfo = new JSONObject();
        lotteryInfo.put("money",lottery);
        lotteryInfo.put("status",sysLotteryRecords.getStatus());
        result.put("lotteryInfo",lotteryInfo);

        return success(result);
    }
}
